﻿Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Linq.Expressions
Imports WPFSearchDataGrid
Imports WPFSearchDataGrid_DAL
Imports WPFSearchDataGrid_Test.Views

Class MainWindow

    Private vm As New ObservableCollection(Of ViewModel)
    Private bgw As New BackgroundWorker

    Public Property View As ObservableCollection(Of ViewModel)
        Get
            Return vm
        End Get
        Set(value As ObservableCollection(Of ViewModel))
            vm = value
        End Set
    End Property

    Public Sub New()
        InitializeComponent()
        vm.Add(New ViewModel())
        AddHandler bgw.DoWork, AddressOf bgw_dowork
        AddHandler bgw.RunWorkerCompleted, AddressOf bgw_runworkercompleted
    End Sub


    Private Sub Window_Loaded(sender As System.Object, e As RoutedEventArgs) Handles MyBase.Loaded
        Try
            Dim ViewSource As Windows.Data.CollectionViewSource = CType(FindResource("ViewSource"), Windows.Data.CollectionViewSource)
            ViewSource.Source = View
        Catch ex As Exception
        End Try
    End Sub

    Private Sub WWSearchDataGrid1_OnFilterChanged(sender As System.Object, e As RoutedEventArgs)
        Dim _record As Record = e.OriginalSource
        bgw.RunWorkerAsync(_record)
    End Sub

    Private Sub bgw_dowork(sender As Object, e As DoWorkEventArgs)
        Dim _record As Record = e.Argument
        e.Result = _record.FilterAsExpression(Of BusinessEntityAddress)()
    End Sub

    Private Sub bgw_runworkercompleted(sender As Object, e As RunWorkerCompletedEventArgs)

        '*** idea here was i could filter local in memory collections. ***

        Dim query As Expression(Of Func(Of BusinessEntityAddress, Boolean)) = e.Result
        Dim BusinessEntityAddresses As Windows.Data.CollectionViewSource = CType(FindResource("BusinessEntityAddresses"), Windows.Data.CollectionViewSource)
        BusinessEntityAddresses.Source = From z In View(0).BusinessEntityAddresses.Where(query.Compile)

        'View(0).Filter(query.Compile)
        'BusinessEntityAddresses.Source = View(0).BusinessEntityAddresses

        '*** or use the compiled expression to requery the Database. ***

        'Dim context = New AdventureWorksEntities()
        'BusinessEntityAddresses.Source = context.BusinessEntityAddresses.Where(query.Compile)
    End Sub

End Class
